package me.zhenqu.redis;

import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * create at: 11-10-31
 *
 * @author Yonghui Chen
 */
public class ThreadBindingRedisOperator {
    private Map<String, Jedis> jedisMap = new HashMap<String, Jedis>();
    private static final ThreadLocal<ThreadBindingRedisOperator> operatorThreadLocal = new ThreadLocal<ThreadBindingRedisOperator>();

    public static ThreadBindingRedisOperator initThread() {
        ThreadBindingRedisOperator old = operatorThreadLocal.get();
        if (old != null) {
            old.free();
        }
        ThreadBindingRedisOperator operator = new ThreadBindingRedisOperator();
        operatorThreadLocal.set(operator);
        return operator;
    }

    private ThreadBindingRedisOperator() {
    }

    public static ThreadBindingRedisOperator getOperator() {
        return operatorThreadLocal.get();
    }

    public Jedis getJedis(String key) {
        Jedis jedis = jedisMap.get(key);
        if (jedis == null || !jedis.isConnected()) {
            jedis = RedisOperator.getOperator(key).getJedisFromPool();
            jedisMap.put(key, jedis);
        }
        return jedis;
    }

    public void free() {
        for (Map.Entry<String, Jedis> jedis : jedisMap.entrySet()) {
            RedisOperator.getOperator(jedis.getKey()).freeResource(jedis.getValue());
        }
        jedisMap.clear();
        operatorThreadLocal.set(null);
    }
}
